<?php

namespace App\Http\Middleware;

use App\Address;
use App\Member;
use Facades\App\WeChat\Facades\WeChatOAuth;
use Closure;

class RegWeChatMember
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(WeChatOAuth::check()) {
            $wxUser = WeChatOAuth::user();
            $openid = $wxUser['id'];
            $member = Member::where('openid',$openid)->first();
            

            if(!$member) {

                //新增会员
                $member = new Member();
                $member->openid = $openid;
                $member->avatar = $wxUser['avatar'];
                $member->nickname = $wxUser['name'];
                $member->sex = $wxUser['original']['sex'];
                $member->save();



            }
            session(['member'=>$member]);
        }
        return $next($request);
    }
}
